package com.weng.cloud.service8881.jaxrs.conf;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
import com.weng.cloud.service8881.jaxrs.service.TestCXFService;
import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.endpoint.Server;
import org.apache.cxf.feature.LoggingFeature;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import org.apache.cxf.jaxrs.provider.json.JSONProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collections;

/**
 * @Author: weng
 * @Date: 2022/5/1
 * @Description: com.weng.cloud.starter.jaxrs
 *
 * @see https://cxf.apache.org/docs/jax-rs-data-bindings.html?spm=a2c6h.13066369.question.23.7f301e25wDhJff
 *
 * jax-rs如果注入的话，spring mvc将接收不到请求，故在这里关闭
 */
//@Configuration
public class JaxRsAutoConfiguration {

    @Resource
    private SpringBus bus;

    @Resource
    private ObjectMapper objectMapper;

    @Bean
    public Server jaxRsServer(){
        JAXRSServerFactoryBean rsEndpoint = new JAXRSServerFactoryBean();
        rsEndpoint.setBus(bus);
        rsEndpoint.setAddress("/");
//        rsEndpoint.setProviders(Arrays.asList(jacksonJsonProvider));
        rsEndpoint.setProviders(Arrays.asList(jacksonJaxbJsonProvider()));
        rsEndpoint.setFeatures(Arrays.asList(new LoggingFeature()));
        rsEndpoint.setServiceBeans(Collections.singletonList(new TestCXFService()));
        return rsEndpoint.create();
    }

    /**
     * 配置一个对象与json转换的工具
     */

    @Bean
    public JacksonJaxbJsonProvider jacksonJaxbJsonProvider() {
        return new JacksonJaxbJsonProvider(objectMapper, JacksonJaxbJsonProvider.DEFAULT_ANNOTATIONS);
    }

/*    @Bean
    public JSONProvider jsonProvider(){
        JSONProvider jsonProvider = new JSONProvider();
//        jsonProvider.setSerializeAsArray(true);
//        jsonProvider.setArrayKeys();
        jsonProvider.setMarshallAsJaxbElement(true);
        return jsonProvider;
    }*/
}
